package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.mapper.ScheduleMapper;
import cn.kgc.vue.vo.ScoreVO;
import cn.kgc.vue.vo.StudentVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Score;
import cn.kgc.vue.service.ScoreService;
import cn.kgc.vue.mapper.ScoreMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @author 11839
* @description 针对表【sys_score】的数据库操作Service实现
* @createDate 2024-06-28 15:23:44
*/
@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score>
    implements ScoreService{

    private final ScheduleMapper scheduleMapper;

    public ScoreServiceImpl(ScheduleMapper scheduleMapper) {
        this.scheduleMapper = scheduleMapper;
    }

    @Override
    public ResponseResult scorePage(QueryCondition<Score> queryCondition) {
        Page<Score> scorePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        String clazz = queryCondition.getSearchParams().getClazz();
        Date examTime = queryCondition.getSearchParams().getExamTime();
        LambdaQueryWrapper<Score> lambda = new QueryWrapper<Score>().lambda();
        lambda.eq(StringUtils.isNotBlank(clazz),Score::getClazz, clazz)
                .eq(examTime!=null,Score::getExamTime, examTime)
                .orderByDesc(Score::getExamTime);

        baseMapper.selectPage(scorePage,lambda);
        long total = scorePage.getTotal();
        List<Score> scores = scorePage.getRecords();


        return ResponseResult.success().data("total", total).data("tableData", scores);
    }

    @Override
    public ResponseResult saveUpdataScore(Score score) {
        //一个成绩表内不能有同一个人 然后有多个相同的科目
        //解决办法 传入的score先查
        String studentNo = score.getStudentNo();
        String examContent = score.getExamContent();
        LambdaQueryWrapper<Score> eq = new QueryWrapper<Score>().lambda()
                .eq(Score::getStudentNo, studentNo)
                .eq(Score::getExamContent, examContent);

        List<Score> scores = baseMapper.selectList(eq);
        if (score.getId()!=null){
            //不为null就是编辑
            baseMapper.updateById(score);
            return ResponseResult.success().message("编辑成功");
        }

        if (scores.size() > 0) {
            return ResponseResult.fail().message("该学号学生已有该科目成绩");
        }
        baseMapper.insert(score);

        return ResponseResult.success().message("添加成功");
    }

    @Transactional
    @Override
    public ResponseResult importStudent(MultipartFile file) throws Exception {
        // 1. 判断传入的文件是否为空
        if (file.isEmpty()) {
            return ResponseResult.fail().message("文件为空，请传入文件");
        }

        // 2. 创建导入参数
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);

        // 3. 使用 try-with-resources 语句来确保 InputStream 在使用后被正确关闭
        try (InputStream inputStream = file.getInputStream()) {
            List<Score> scores = ExcelImportUtil.importExcel(inputStream, Score.class, importParams);
            for (Score score : scores) {
                String studentNo = score.getStudentNo();
                String examContent = score.getExamContent();
                // 4. 使用 LambdaQueryWrapper 查询数据库中是否已有相同学生编号和考试内容的成绩
                LambdaQueryWrapper<Score> eq = new QueryWrapper<Score>().lambda()
                        .eq(Score::getStudentNo, studentNo)
                        .eq(Score::getExamContent, examContent);

                List<Score> existingScores = baseMapper.selectList(eq);
                // 5. 如果已有该学生该科目的成绩，则返回失败信息
                if (!existingScores.isEmpty()) {
                    return ResponseResult.fail().message("学号 " + studentNo + " 的学生已有"+examContent+"成绩");
                }
                // 6. 插入新的成绩
                baseMapper.insert(score);
            }

        } catch (Exception e) {
            // 7. 异常处理
            return ResponseResult.fail().message("导入过程中发生错误: " + e.getMessage());
        }

        return ResponseResult.success().message("导入成功");
    }

    @Override
    public ResponseResult exportStudent(HttpServletResponse response, Map<String, Object> exportParam) throws IOException {

        Object clazz =  exportParam.get("clazz");
        Object examTime =  exportParam.get("examTime");
        LambdaQueryWrapper<Score> lambda = new QueryWrapper<Score>().lambda();
        lambda.eq(ObjectUtils.isNotNull(clazz),Score::getClazz, clazz)
                .eq(ObjectUtils.isNotNull(examTime),Score::getExamTime, examTime);

        List<Score> scores = baseMapper.selectList(lambda);

        //创建导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("学生考试成绩表");
        exportParams.setSheetName(clazz+"成绩表");

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, Score.class, scores);
        ServletOutputStream outputStream = response.getOutputStream();

        // 写出工作簿
        sheets.write(outputStream);
        sheets.close();
        outputStream.close();

        return ResponseResult.success().message("导出成功");
    }

    @Override
    public ResponseResult scoreDataVisual() {

        List<Score> scores = baseMapper.selectScoreDataVisual();
        return ResponseResult.success()
                .data("list", scores);
    }

    @Override
    public ResponseResult scoreVisual() {
        List<Score> scores = baseMapper.selectScoreVisual();
        return ResponseResult.success().data("scoreList",scores);
    }

    @Override
    public ResponseResult classVisual() {
        List<ScoreVO> scoreVOS = baseMapper.selectSumScore();
        return ResponseResult.success().data("scoreVOList",scoreVOS);
    }

    @Override
    public ResponseResult sumClazzPeople() {
        List<StudentVo> studentVos = baseMapper.sumClazzPeople();
        studentVos.forEach(studentVo -> {
            System.out.println("studentVo = " + studentVo);
        });
        return ResponseResult.success().data("sumClazzPeople",studentVos);

    }

    @Override
    public ResponseResult goodPeople() {
        //我要拿到 优秀人数的排名  总分在85分以上的为优秀
        //先得查出 哪些人是 优秀的
        //这些优秀的是哪个班的
        List<StudentVo> studentVos = baseMapper.goodPeople();
        studentVos.forEach(studentVo -> {
            String clazz = studentVo.getClazz();
            String classNo = scheduleMapper.selectById(clazz).getClassNo();
            studentVo.setClassName(classNo);
        });

        studentVos.forEach(studentVo -> {
            System.out.println("studentVo = " + studentVo);
        });

        return ResponseResult.success().data("goodPeople",studentVos);
    }


}




